package com.asseco.mio.core.webapp.controller;

import com.asseco.mio.UserInstitution;
import com.asseco.mio.codex.Institution;
import com.asseco.mio.codex.UserInstitutionsForm;
import com.asseco.mio.codex.UserInstitutionsForm2;
import com.asseco.persistence.service.HibernateUtil;
import org.appfuse.model.User;
import org.appfuse.service.UserManager;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.appfuse.model.LabelValue;
import org.appfuse.service.GenericManager;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Qualifier;

/**
 * Implementation of <strong>SimpleFormController</strong> that interacts with
 * the {@link UserManager} to retrieve/persist values to the database.
 *
 * <p><a href="UserFormController.java.html"><i>View Source</i></a>
 *
 * @author <a href="mailto:matt@raibledesigns.com">Matt Raible</a>
 */
@Controller
@RequestMapping("/userinstitutions*")
public class UserInstitutionController extends BaseFormController {

    private UserManager userManager = null;
    private GenericManager<Institution, String> institutionManager = null;
    private GenericManager<UserInstitution, String> userInstitutionManager = null;

   
    @Autowired
    public void setUserManager(UserManager userManager) {
        this.userManager = userManager;
    }

    @Autowired
    public void setInstitutionManager(@Qualifier("institutionManager") GenericManager<Institution, String> institutionManager) {
        this.institutionManager = institutionManager;
    }

    @Autowired
    public void setUserInstitutionManager(@Qualifier("userInstitutionManager") GenericManager<UserInstitution, String> userInstitutionManager) {
        this.userInstitutionManager = userInstitutionManager;
    }

    public UserInstitutionController() {
        setCancelView("redirect:/mainMenu");
        setSuccessView("redirect:/userinstitutions");
    }

    @ModelAttribute
    public UserInstitutionsForm2 userInstitutionsForm() {
        Set set1 = new HashSet(userInstitutionManager.getAll());
        Set set2 = new HashSet(institutionManager.getAll());
        UserInstitutionsForm2 x = new UserInstitutionsForm2(new User(), set1,set2);
        return x;
       
    }

    @RequestMapping(method = RequestMethod.POST)
    public String onSubmit(UserInstitutionsForm userInstitutionsForm, BindingResult errors, HttpServletRequest request,
                           HttpServletResponse response)
            throws Exception {

            long id = (long) Integer.parseInt(request.getParameter("id"));
               
        
        User tempUser = userManager.get(id);

        userInstitutionsForm.getUser().setFirstName(tempUser.getFirstName());
        userInstitutionsForm.getUser().setLastName(tempUser.getLastName());
        userInstitutionsForm.getUser().setUsername(tempUser.getUsername());
        userInstitutionsForm.getUser().setId(id);

        Session session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();

        Criteria criteria  = session.createCriteria(UserInstitution.class).add(Restrictions.like("user", tempUser));
        List result = criteria.list();
        session.getTransaction().commit();
        List allInstitutions = getAllActiveInstitutions(institutionManager.getAll());

        for(int i = 0; i<result.size(); i++){
            UserInstitution tempInstitution = (UserInstitution) result.get(i);
            for (int j=0; j<allInstitutions.size(); j++){
                Institution inst = (Institution) allInstitutions.get(j);
                if(inst.equals(tempInstitution.getInstitution())){
                    allInstitutions.remove(j);
                    break;
                }
            }
        }
        //UserInstitutionsForm x = new UserInstitutionsForm(tempUser,result,allInstitutions);
        //ModelAndView view = new ModelAndView("userinstitutions", "userInstitutionsForm", x);


        return "userinstitutions";
    }

    @ModelAttribute
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST})
    public UserInstitutionsForm2 showForm(HttpServletRequest request, HttpServletResponse response)
            throws Exception {

             long id = (long) Integer.parseInt(request.getParameter("id"));

        UserInstitutionsForm2 userInstitutionsForm = this.userInstitutionsForm();
        User tempUser = userManager.get(id);

           userInstitutionsForm.setUser(tempUser);

        Session session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();

        Criteria criteria  = session.createCriteria(UserInstitution.class).add(Restrictions.like("user", tempUser));
        List result = criteria.list();
        session.getTransaction().commit();
        List allInstitutions = getAllActiveInstitutions(institutionManager.getAll());

        for(int i = 0; i<result.size(); i++){
            UserInstitution tempInstitution = (UserInstitution) result.get(i);
            for (int j=0; j<allInstitutions.size(); j++){
                Institution inst = (Institution) allInstitutions.get(j);
                if(inst.equals(tempInstitution.getInstitution())){
                    allInstitutions.remove(j);
                    break;
                }
            }
        }
        Set set1 = new HashSet(result);
        Set set2 = new HashSet(allInstitutions);
       
        UserInstitutionsForm2 x = new UserInstitutionsForm2(tempUser,set1,set2);


        return x;
      
    }
   
    public List getAllActiveInstitutions(List<Institution> list) {

        List result = new ArrayList();
        for (int i = 0; i < list.size(); i++) {
            Institution ga = list.get(i);
            if (ga.getStatus() == true) {
                result.add(ga);
            }

        }
result = (List<LabelValue>) result;
        return result;
    }
}

